<template>
  <!-- 拖拽文件 -->
  <div class="upload-container">
    <!-- 拖拽区域 -->
    <div class="drop-area" @dragover.prevent="handleDragOver" @dragleave="handleDragLeave" @drop.prevent="handleDrop"
      @click="triggerFileInput" :class="{ 'drag-active': isDragging }">
      <p>拖拽文件到此处或点击此处</p>
      <!-- 点击上传按钮 -->
      <input type="file" ref="fileInput" @change="handleFileChange" style="display: none" multiple />
    </div>
    <!-- 上传文件列表 -->
    <div class="file-list" v-if="files.length > 0">
      <div v-for="(file, index) in files" :key="index" class="file-item">
        <span>{{ file.name }}</span>
        <span class="file-size">({{ formatFileSize(file.size) }})</span>
        <button @click="removeFile(index)" class="remove-btn">×</button>
      </div>
    </div>
    <!-- 上传按钮 -->
    <button @click="uploadFiles" class="upload-btn" :disabled="files.length === 0">
      上传文件
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const isDragging = ref(false);
const files = ref([]);
const fileInput = ref(null);



// 触发文件选择对话框
const triggerFileInput = () => {
  fileInput.value.click();
};

// 处理文件选择
const handleFileChange = (e) => {
  const selectedFiles = Array.from(e.target.files);
  addFiles(selectedFiles);
};

// 处理拖拽进入
const handleDragOver = () => {
  isDragging.value = true;
};

// 处理拖拽离开
const handleDragLeave = () => {
  isDragging.value = false;
};


// 处理拖拽放下
const handleDrop = (e) => {
  isDragging.value = false;
  const droppedFiles = Array.from(e.dataTransfer.files);
  addFiles(droppedFiles);
};

// 添加文件到列表
const addFiles = (newFiles) => {
  const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
  const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
  // 过滤掉重复文件
  const uniqueFiles = newFiles.filter(newFile => {
    !files.value.some(existingFile =>
      existingFile.name === newFile.name &&
      existingFile.size === newFile.size
    )
    if (!allowedTypes.includes(file.type)) {
      alert(`文件 ${file.name} 类型不支持`);
      return false;
    }
    if (existingFile.size > MAX_FILE_SIZE) {
      alert(`文件 ${file.name} 大小超过限制`);
      return false;
    }
  }

  );

  files.value = [...files.value, ...uniqueFiles];
};

// 移除文件
const removeFile = (index) => {
  files.value.splice(index, 1);
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 上传文件
const uploadFiles = async () => {
  if (files.value.length === 0) return;

  try {
    // 这里替换为你的上传逻辑
    const formData = new FormData();
    files.value.forEach(file => {
      formData.append('files', file);
    });

    // 示例：使用fetch API上传
    const response = await fetch('你的上传接口', {
      method: 'POST',
      body: formData
    });

    if (response.ok) {
      alert('上传成功！');
      files.value = []; // 清空文件列表
    } else {
      throw new Error('上传失败');
    }
  } catch (error) {
    console.error('上传出错:', error);
    alert('上传出错，请重试');
  }
};
</script>

<style scoped>
.upload-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.drop-area {
  border: 2px dashed #ccc;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.drop-area:hover,
.drag-active {
  border-color: #4CAF50;
  background: rgba(red, green, blue, alpha);
  background-color: #f8f8f8;
}

.drop-area p {
  margin-bottom: 15px;
}

button {
  padding: 8px 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin: 5px;
}

button:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.file-list {
  margin-top: 20px;
}

.file-item {
  display: flex;
  align-items: center;
  padding: 8px;
  border-bottom: 1px solid #eee;
}

.file-size {
  color: #777;
  margin-left: 10px;
  font-size: 0.9em;
}

.remove-btn {
  margin-left: auto;
  background-color: #f44336;
  width: 24px;
  height: 24px;
  padding: 0;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-btn {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: 1em;
}
</style>